package com.study.spaoplog.controller;

import com.study.spaoplog.anno.NeedLock;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author study
 * @version 1.0
 * @date 2021/6/8 17:15
 */
@Slf4j
@RestController
@RequestMapping("/annolock/")
public class AnnoLockController {


    @Autowired(required = false)
    private CuratorFramework zkClient;
    private Integer numdate = 0;
    private Integer num = 0;

    @GetMapping("/datewithLock")
    public LocalDateTime date() throws Exception {
        InterProcessMutex lock = new InterProcessMutex(zkClient, "/lockPath");
        // if (lock.acquire(1, TimeUnit.SECONDS)) {
        try {
            lock.acquire();
            numdate = numdate + 1;
            System.out.println(numdate);
            shortSleep();
            // do some work inside of the critical section here
            return LocalDateTime.now();
        } finally {
            lock.release();
        }
    }

    @NeedLock
    @GetMapping("/str")
    public String str() {
        num = num + 1;
        shortSleep();
        System.out.println(num);
        return RandomStringUtils.randomNumeric(4) + "_" + num;
    }

    private void shortSleep() {
        try {
            TimeUnit.MILLISECONDS.sleep(ThreadLocalRandom.current().nextInt(1, 100));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
